#define _CRT_SECURE_NO_WARNINGS
#include"string.h"
namespace My_string
{
	const size_t string::npos = -1;

	string::string(const char* str)
		:_size(strlen(str))
	{
		_str = new char[_size + 1];
		_capacity = _size;
		strcpy(_str, str);
		//cout << "string::string(const char* str)" << endl;
	}
	string::string(const string& s)
	{
		_str = new char[s._size + 1];
		strcpy(_str, s._str);
		_size = s._size;
		_capacity = s._capacity;
		//cout << "copy" << endl;
	}
	string::~string()
	{
		delete[] _str;
		_str = nullptr;
		_size = 0;
		_capacity = 0;
		//cout << "~" << endl;
	}
	size_t string::size()const
	{
		return _size;
	}
	void string::reserve(size_t s)
	{
		char* tmp = new char[s + 1];
		strcpy(tmp, _str);
		delete[] _str;
		_str = tmp;
		_capacity = s;
	}
	string& string::operator=(const string& s)
	{
		if (this != &s)
		{
			char* tmp = new char[s._capacity + 1];
			strcpy(tmp, s._str);
			delete[] _str;
			_str = tmp;
			_size = s._size;
			_capacity = s._capacity;
		}
		
		return *this;
	}
	const char* string::c_str()const
	{
		return this->_str;
	}
	string::iterator string::begin()
	{
		return _str;
	}
	string::iterator string::end()
	{
		return _str + _size;
	}
	string::const_iterator string::begin()const
	{
		return _str;
	}
	string::const_iterator string::end()const
	{
		return _str + _size;
	}
	void string::push_back(char ch)
	{
		if (_size == _capacity)
		{
			size_t newcapacity = _capacity == 0 ? 4 : _capacity * 2;
			reserve(newcapacity);
		}
		_str[_size] = ch;
		_str[_size+1] = '\0';
		_size++;
	}
	void string::append(const char* str)
	{
		size_t len = strlen(str);
		if (len + _size > _capacity)
		{
			reserve(len + _size + 1);
		}
		strcpy(_str + _size, str);
		_size = _size + len;
	}
	void string::insert(size_t pos, char ch)
	{
		if (pos == _size)
		{
			push_back(ch);
		}
		if (_size == _capacity)
		{
			size_t newcapacity = _capacity == 0 ? 4 : _capacity * 2;
			reserve(newcapacity);
		}
		size_t end = _size + 1;
		while(end > pos)
		{
			_str[end+1] = _str[end];
			end--;
		}
		_str[pos] = ch;
		_size++;
	}
	void string::erase(size_t pos, size_t len)
	{
		if (len > _size - pos)
		{
			_str[pos] = '\0';
			_size = pos;
		}
		else
		{
			strcpy(_str + pos, _str + pos + len);
			_size = _size - len;
		}
		
	}
	size_t string::find(char ch, size_t pos)
	{
		for (int i = pos; i < _size; i++)
		{
			if (_str[i] == ch)
			{
				return i;
			}
		}
		return npos;
	}
	size_t string::find(const char* sub, size_t pos)
	{
		char* p = strstr(_str + pos, sub);
		return p - _str;
	}

}